﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Mvc;
using Microsoft.Web.WebSockets;

namespace AngularCabasi.Controllers
{
    public class CommunicationController : Controller
    {
        //
        // GET: /Communication/

        public HttpResponseMessage Get()
        {
            HttpContext.AcceptWebSocketRequest(new ChatClient());
            return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols);
        }

        public class ChatClient : WebSocketHandler
        {
            public readonly Guid ConnectionId = Guid.NewGuid();
            private static WebSocketCollection chatClients = new WebSocketCollection();

            public override void OnOpen()
            {
                chatClients.Add(this);
                chatClients.Broadcast(
                    "Client joined: " + ConnectionId.ToString()
                );
            }

            public override void OnClose()
            {
                chatClients.Broadcast(
                    "Client left: " + ConnectionId.ToString()
                );
                chatClients.Remove(this);
            }

            public override void OnMessage(string message)
            {
                chatClients.Broadcast(
                    ConnectionId.ToString() + " said: " + message
                );
            }
        }
    }
}
